#!/usr/bin/env bash

# Program：PHP lint and code style
# Default the PSR1 and PSR2 rules are used.
# use php-cs-fixer  https://github.com/FriendsOfPHP/PHP-CS-Fixer

path=`dirname $0`
files=`git status -suno`
cd $path && cd ..
syntax_error=0
code_style=0
exit_num=0

phpfixer=`which php-cs-fixer`
bin=/usr/local/bin/php-cs-fixer

# install php-cs-fixer
if [[ $phpfixer = "" ]]; then
    echo "Preparing to install php-cs-fixer ..."
    sudo curl -L https://cs.sensiolabs.org/download/php-cs-fixer-v2.phar -o ${bin};
    sudo chmod a+x $bin
    echo "php-cs-fixer has been installed."
fi
echo "BACKEND TEAM CODE STYLE CHECKING...."
for file in ${files[@]}; do
    if [[ $file =~ .*\.php ]];then
        error=$(php -l $file 2>&1 | grep "Parse error")
        if [[ $error != "" ]]; then
            echo "[Error] Syntax error found in file: $file "
            syntax_error=1
        else
            # By default the PSR1 and PSR2 rules are used.
            style=$(php-cs-fixer fix $file 2>&1 | grep ")")
            if [ "$style" != "" ]; then
                code_style=1
                echo "[Fixed] PHP Code Style fixed in file: $file "
            fi
        fi
    fi
done
if [ $syntax_error -ge 1 ]; then
    exit_num=1
    echo "什么鬼，居然有语法错误？赶紧改了再提交..."
else
    echo "Congratulations!!!,No syntax error found."
fi
if [ $code_style -ge 1 ];then
    exit_num=1
    echo "你的代码不符合后端团队代码风格，已被拒绝."
    echo "但出于人道主义考虑，已经帮你修复代码风格，请确认(git diff)后再提交(git add,git commit)"
else
    echo "Congratulations!!!,No code style need fix."
fi
exit $exit_num
